package com.hksj.data.tdengine.restful.write;

import com.hksj.data.tdengine.conf.TDengineProperties;
import com.hksj.data.tdengine.operation.TDEngineDataWriter;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.influxdb.dto.Point;

import java.io.IOException;
import java.net.URI;
import java.util.List;

/**
 * @author zengke
 * @version 1.0
 * @see SchemalessTDengineDataWriter
 * @since 2025/08/14 17:13
 */
@Slf4j
public class SchemalessTDengineDataWriter implements TDEngineDataWriter {

    private final TDengineProperties.RestfulConnector connector;

    private final String database;

    public SchemalessTDengineDataWriter(TDengineProperties.RestfulConnector connector,
                                        String database){
        this.connector = connector;
        this.database = database;
    }


    @Override
    public void write(Point point) {
        writeRaw(point.lineProtocol(), database);
    }

    @Override
    public void writeBatch(List<Point> points) {
        if (points == null || points.isEmpty()) {
            return;
        }

        // 将多个 Point 转为多行 Line Protocol（每行一条）
        StringBuilder batch = new StringBuilder();
        for (Point point : points) {
            String line = point.lineProtocol();
            if (!line.trim().isEmpty()) {
                batch.append(line).append("\n"); // 每条数据换行
            }
        }

        writeRaw(batch.toString(), database);
    }


    /**
     * 直接写入原始 Line Protocol 字符串
     */
    public void writeRaw(String line,String  database) {
        URI endpoint = connector.selectURI();
        String url = endpoint.toString().endsWith("/")
                ? endpoint.toString() + "influxdb/v1/write?db=" + database
                : endpoint.toString() + "/influxdb/v1/write?db=" + database;

        RequestBody body = RequestBody.create(connector.getLineProtocolMediaType(),line);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        try (Response response = connector.getHttpClient().newCall(request).execute()){

            if (!response.isSuccessful()) {
                String bodyStr = response.body() != null ? response.body().string() : "null";

                log.info("TDengine write failed: " + response + ", body: " + bodyStr);
            }
        } catch (IOException e) {
            log.error("TDengine write failed: " + e.getMessage(), e);
        }
    }
}
